package cn.e4j.modular.crm.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.common.exception.BizExceptionEnum;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.PageReData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.reqres.response.SuccessResponseData;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.core.util.LangUtils;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.crm.mapper.GwakTMapper;
import cn.e4j.modular.crm.mapper.GwamTMapper;
import cn.e4j.modular.crm.mapper.GwaoTMapper;
import cn.e4j.modular.crm.mapper.GwdaTMapper;
import cn.e4j.modular.crm.service.impl.GwdaTServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商品经营范围管理
 * Created by shixc on 2019-2-2
 */
@Controller
@RequestMapping("/crm/gwdc001")
public class Gwdc001Controller extends BaseController {

    @Autowired
    private GwdaTServiceImpl gwdaTService;


    @Autowired
    private GwakTMapper gwakTMapper;

    @Autowired
    private GwamTMapper gwamTMapper;

    @Autowired
    private GwdaTMapper gwdaTMapper;

    @Autowired
    private GwaoTMapper gwaoTMapper;

    /**
     * 跳转商品经营范围管理页面
     */
    @RequiresPermissions("crm:gwdc001:init")
    @RequestMapping(value = {"", "init"})
    public String index() {
        return "/pc/crm/gwdc001.html";
    }

    /**
     * 查询商品经营范围信息列表
     */
    @RequestMapping("/getList")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData getList(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        ShiroUser user = ShiroKit.getUser();
        inDto.put("GWDAENT", user.getDBC());
        inDto.put("lang", LangUtils.getLang(user.getLANG()));
        List<Map<String, Object>> result = gwdaTService.getList(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 新增
     */
    @RequestMapping("/add")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData add(GwdaT gwdaT) {
        gwdaTService.add(gwdaT);
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @RequestMapping("/edit")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData edit(GwdaT gwdaT) {
        gwdaTService.edit(gwdaT);
        return SUCCESS_TIP;
    }

    /**
     * 删除
     */
    @RequestMapping("/del")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData del(GwdaT gwdaT) {
        gwdaTService.delete(gwdaT);
        return SUCCESS_TIP;
    }

    /**
     * 批量删除数据
     */
    @RequestMapping("/deleteDataBatch")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData deleteDataBatch(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdaT> gwdaTList = inDto.getReqList(GwdaT.class);
        gwdaTService.delDataBatch(gwdaTList);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/exportsData", method = RequestMethod.GET)
    @RequiresPermissions("crm:gwdc001:init")
    public void exportsData(ModelMap map, HttpServletRequest request, HttpServletResponse response, @DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        ShiroUser user = ShiroKit.getUser();
        inDto.put("lang", LangUtils.getLang(user.getLANG()));
        inDto.put("GWDAENT", user.getDBC());
        List<Map<String, Object>> list = gwdaTService.getList(null, inDto);
        ExportParams params = new ExportParams(null, "商品经营范围数据", ExcelType.XSSF);
        //params.setFreezeCol(2);
        map.put(NormalExcelConstants.FILE_NAME, "商品经营范围数据");
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put(NormalExcelConstants.CLASS, Gwdc001Export.class);
        map.put(NormalExcelConstants.PARAMS, params);
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    @RequestMapping(value = "/importsData", method = RequestMethod.POST)
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData importsData(MultipartFile file, ModelMap map) {
        ShiroUser user = ShiroKit.getUser();
        Dto inDto = Dtos.newDto();
        ImportParams params = new ImportParams();
        params.setTitleRows(0);//表格标题行数,默认0
        params.setHeadRows(1);//表头行数,默认1
        params.setStartRows(0);//字段真正值和列标题之间的距离 默认0
        int count = 0;
        int account = 0;
        String message1 = "客户";
        String message2 = "品号";
        String message3 = "系列";
        try {
            List<GwdaT> list = ExcelImportUtil.importExcel(file.getInputStream(), GwdaT.class, params);
            for (GwdaT gwdaT : list) {
                if (gwdaT.getGWDA002() != null && gwdaT.getGWDA003() != null && gwdaT.getGWDA007() != null) {//客户、品号、产品系列不为空
                    QueryWrapper<GwakT> gwakTUpdateWrapper = new QueryWrapper<>();
                    gwakTUpdateWrapper.eq("GWAKENT", user.getDBC());
                    gwakTUpdateWrapper.eq("GWAK001", gwdaT.getGWDA002());
                    int gwak = gwakTMapper.selectList(gwakTUpdateWrapper).size();
                    int gwam = 0;
                    if (!gwdaT.getGWDA003().equals("*")) {
                        QueryWrapper<GwamT> gwamTUpdateWrapper = new QueryWrapper<>();
                        gwamTUpdateWrapper.eq("GWAMENT", user.getDBC());
                        gwamTUpdateWrapper.eq("GWAM001", gwdaT.getGWDA003());
                        gwamTUpdateWrapper.eq("GWAM004", gwdaT.getGWDA007());
                        gwam = gwamTMapper.selectList(gwamTUpdateWrapper).size();
                    } else {
                        gwam = 1;
                    }
                    QueryWrapper<GwaoT> gwaoTUpdateWrapper = new QueryWrapper<>();
                    gwaoTUpdateWrapper.eq("GWAOENT", user.getDBC());
                    gwaoTUpdateWrapper.eq("GWAO001", gwdaT.getGWDA007());
                    int gwao = gwaoTMapper.selectList(gwaoTUpdateWrapper).size();
                    if (gwak > 0 && gwam > 0 && gwao > 0) {
                        if (gwdaT.getGWDA005() == null) {
                            gwdaT.setGWDA005("Y");
                        }
                        if (gwdaT.getGWDA006() == null) {
                            gwdaT.setGWDA006("Y");
                        }
                        Dto dto = gwdaTMapper.getMaxGwda001();
                        gwdaT.setGWDA001(dto.getBigDecimal("GWDA001"));
                        gwdaT.setGWDA004(LocalDate.now());
                        gwdaT.setGWDAENT(user.getDBC());
                        gwdaT.setGWDAACTI("Y");
                        gwdaT.insert();
                        count++;
                    } else {
                        if (gwak == 0) {
                            message1 = message1 + gwdaT.getGWDA002() + "、";
                        }
                        if (gwam == 0) {
                            message2 = message2 + gwdaT.getGWDA003() + "、";
                        }
                        if (gwao == 0) {
                            message3 = message3 + gwdaT.getGWDA007() + "、";
                        }
                        continue;
                    }
                } else {
                    continue;
                }
                account++;
            }
            if (count != list.size()) {
                if (!message1.equals("客户")) {
                    message1 = message1.substring(0, message1.length() - 1);
                    message1 = message1 + "不存于有效的客户资料中,";
                } else {
                    message1 = "";
                }
                if (!message2.equals("品号")) {
                    message2 = message2.substring(0, message2.length() - 1);
                    message2 = message2 + "不存于有效的产品资料中,";
                } else {
                    message2 = "";
                }
                if (!message3.equals("系列")) {
                    message3 = message3.substring(0, message3.length() - 1);
                    message3 = message3 + "不存于有效的系列资料中,";
                } else {
                    message3 = "";
                }
                String message = "";
                if (count > 0) {
                    message = message1 + message2 + message3 + "请检查!有" + count + "笔导入成功。";
                    return new ErrorResponseData(402,
                            message);
                } else {
                    message = message1 + message2 + message3 + "请检查!";
                    return new ErrorResponseData(401,
                            message);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorResponseData(BizExceptionEnum.SERVER_ERROR.getCode(),
                    BizExceptionEnum.SERVER_ERROR.getMessage());
        }
        return SUCCESS_TIP;
    }

    /**
     * 校验产品编号是否存在
     */
    @RequestMapping("/checkGwda003")
    @ResponseBody
    public ResponseData checkGwda003(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto result = gwdaTService.checkGwda003(inDto);
        return new SuccessResponseData(result);
    }

    /**
     * 校验产品系列是否存在
     */
    @RequestMapping("/checkGwda007")
    @ResponseBody
    public ResponseData checkGwda007(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        Dto result = gwdaTService.checkGwda007(inDto);
        return new SuccessResponseData(result);
    }

    /**
     * 查询商品经营范围信息列表
     */
    @RequestMapping("/getGwakData")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData getGwakData(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        ShiroUser user = ShiroKit.getUser();
        inDto.put("ENT", user.getDBC());
        inDto.put("LANG", LangUtils.getLang(user.getLANG()));
        List<Dto> dtoList = null;
        if(!inDto.getString("keyword").equals("")){
            String[] GWAE001 = inDto.getString("keyword").split(",");
            dtoList = new ArrayList<>();
            for(String gwae001 : GWAE001){
                Dto defaultDto = Dtos.newDto();
                defaultDto.put("GWAE001", gwae001);
                dtoList.add(defaultDto);
            }
        }
        inDto.put("keyword",dtoList);
        List<Map<String, Object>> result = gwdaTService.getGwakData(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 查询商品经营范围信息列表
     */
    @RequestMapping("/getGwamData")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData getGwamData(@DtoParam DtoWapper dtoWapper) {
        Page<Object> page = dtoWapper.getPage();
        Dto inDto = dtoWapper.getDto();
        ShiroUser user = ShiroKit.getUser();
        inDto.put("ENT", user.getDBC());
        inDto.put("LANG", LangUtils.getLang(user.getLANG()));
        List<Dto> dtoList = null;
        if(!inDto.getString("keyword").equals("")){
            String[] GWAO001 = inDto.getString("keyword").split(",");
            dtoList = new ArrayList<>();
            for(String gwao001 : GWAO001){
                Dto defaultDto = Dtos.newDto();
                defaultDto.put("GWAO001", gwao001);
                dtoList.add(defaultDto);
            }
        }
        inDto.put("keyword",dtoList);
        List<Map<String, Object>> result = gwdaTService.getGwamData(page, inDto);
        return new PageReData(page, result);
    }

    /**
     * 新增
     */
    @RequestMapping("/addData")
    @RequiresPermissions("crm:gwdc001:init")
    @ResponseBody
    public ResponseData addData(@DtoParam DtoWapper dtoWapper) {
        Dto inDto = dtoWapper.getDto();
        List<GwdaT> gwdaTList = inDto.getReqList(GwdaT.class);
        gwdaTService.addData(gwdaTList);
        return SUCCESS_TIP;
    }
}
